﻿/*
    This file is part of News Worm.

    News Worm is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    News Worm is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with News Worm.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.IO;
using System.Net;

namespace NewsWorm {
    internal static class UrlShortener {
        internal static string Shorten( string url ) {
            try {
                string retval = "";
                HttpWebRequest httpWebRequest =
                    (HttpWebRequest)WebRequest.Create( "https://www.googleapis.com/urlshortener/v1/url" );
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "POST";

                using ( var streamWriter = new StreamWriter( httpWebRequest.GetRequestStream() ) ) {
                    string json = "{\"longUrl\":\"" + url + "\"}";
                    streamWriter.Write( json );
                }

                HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using ( var streamReader = new StreamReader( httpResponse.GetResponseStream() ) ) {
                    string responseText = streamReader.ReadToEnd();
                    retval = ParseResponseJson( responseText );
                }

                return retval;

            } catch {
                return url;
            }
        }

        private static string ParseResponseJson( string json ) {
            int i = json.IndexOf( "http://", 0, StringComparison.OrdinalIgnoreCase );
            string tmp = json.Substring( i );
            string[] arr = tmp.Split( ',' );
            string url = arr[0].Replace( "\"", " " ).Trim();

            return url;
        }
    }
}
